import React, { useEffect } from 'react';
import { Routes, Route, Navigate, useLocation, useNavigate } from 'react-router-dom'
import Login from './views/Login';
import Notfind from './views/Notfind';
import Layout from './views/layout/Index';
import './App.scss';
import store from 'store';
import { useAppSelector } from '@/store/hooks/index';
import { message } from 'antd'
import routes from '@/router/routes'

import { getAllcheckedKeysFn } from '@/utils/common';
console.log('AllcheckedKeys', getAllcheckedKeysFn(routes))
// 获取所有的routes中path 组成的数组
const allCheckedkey = getAllcheckedKeysFn(routes)


// 获取本地登录时存的token 
// 方式1: 
// console.log(store.get('userinfo').token);
// 方式2:
// 使用rtk 中的数据token  const store = useAppSelector(state => state);   
// console.log(getallpathFn(routes));

function App() {
  const store = useAppSelector(state => state);
  let token = store.userinfo.token;
  const [messageApi, contextHolder] = message.useMessage();

  //从redux中 获取该用户可以访问的菜单项
  //console.log('checkedkeys', store.userinfo.checkedkeys);
  const userCheckedKeys = store.userinfo.checkedkeys
  // 获取当前的路由信息, 然后监听该地址栏中的路由信息的变化, 进而判断该用户是否可以访问该路由
  const loc = useLocation()
  // 获取当前的路由函数
  const navigate = useNavigate()
  useEffect(() => {
    //  判断 如果当前地址栏中的路由在总路由里面, 但是不在当前用户的路由数组中,
    // 说明该用户没有权限访问该路由
    if (allCheckedkey.includes(loc.pathname) &&
      userCheckedKeys.length != 0
      && !userCheckedKeys.includes(loc.pathname)) {
      messageApi.open({
        type: 'error',
        content: '您没有权限访问!!!',
        duration: 1,
        onClose() {
          // 返回输入地址前的路由
          navigate(-1)
        }
      })
    }
    // console.log('loc', loc.pathname);

  }, [loc.pathname])


  return (
    <div className="App">
      {contextHolder}
      <Routes>
        {/* 通过判断本地的token, 进而决定是否匹配正确的路由 */}
        {/* <Route path='/login' element={<Login />}></Route>
        <Route path='/*' element={<Layout></Layout>}></Route>
        <Route path='*' element={<Notfind></Notfind>}></Route> */}
        <Route path='/login' element={token ?
          <Navigate to='/' /> : <Login />}></Route>
        <Route path='/*' element={token ? <Layout></Layout> : <Navigate to='/login' />}></Route>
        <Route path='*' element={<Notfind></Notfind>}></Route>
      </Routes>
    </div >
  );
}

export default App;
